package com.duing.listnode;

public class ListNode {

    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
        next = null;
    }

    public int getVal() {
        return val;
    }

    public void setVal(int val) {
        this.val = val;
    }

    public ListNode getNext() {
        return next;
    }

    public void setNext(ListNode next) {
        this.next = next;
    }

    //数组转换成链表
    public static ListNode arrayToListNode(int[] s) {
        //生成链表的根节点，并将数组的第一个元素的值赋给链表的根节点
        ListNode root = new ListNode(s[0]);
        //生成另一个节点，并让other指向root节点，other在此作为一个临时变量，相当于指针
        ListNode tmp = root;
        //由于已给root赋值，所以i从1开始
        for (int i = 1; i < s.length; i++) {
            //每循环一次生成一个新的节点,并给当前节点赋值
            ListNode newNode = new ListNode(s[i]);
            //将other的下一个节点指向生成的新的节点
            tmp.next = newNode;
            //将other指向最后一个节点(other的下一个节点)  other=other.getNext();
            tmp = newNode;
        }
        return root;
    }

    /**
     * 给一个链表加环
     */
    public static void toCycle(ListNode node, int pos) {
        int cnt = 0;
        ListNode cycleNode = null;
        while (true) {
            if (cnt == pos) {
                cycleNode = node;
            }
            if (node.next == null) {
                node.next = cycleNode;
                return;
            }
            node = node.next;
            cnt++;
        }
    }


    public static ListNode mergeListNode(ListNode one, ListNode two) {
        if (one == null) return two;
        if (two == null) return one;

        ListNode tmp = one;
        while (tmp.next != null) {
            tmp = tmp.next;
        }
        tmp.next = two;
        return one;
    }

    public static void print(ListNode node) {
        while (node != null) {
            System.out.print(node.val);
            if (node.next != null) {
                System.out.print("->");
            }
            node = node.next;
        }
        System.out.println();
    }
}
